/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.parsers.PlainTextExtractor;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.GlobalProperties;
import com.blandware.atleap.webapp.util.core.ImageUtil;
import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.apache.commons.validator.GenericValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletContext;
import java.io.ByteArrayInputStream;
import java.util.List;

/**
 * <p>Creates new content resource
 * </p>
 * <p><a href="CreateContentResourceAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.34 $ $Date: 2007/12/23 17:13:04 $
 * @struts.action path="/core/contentResource/create"
 * name="uploadContentResourceForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentResource-create"
 * @struts.action-forward name="inputForward"
 * path="/core/contentResource/callCreate.do"
 * redirect="true"
 * @struts.action-forward name="callCreateImage"
 * path="/core/contentResource/image/callCreate.do"
 * @struts.action-forward name="callCreateFile"
 * path="/core/contentResource/file/callCreate.do"
 * @struts.action-forward name="callCreateDocument"
 * path="/core/contentResource/document/callCreate.do"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 * @struts.action-forward name="closeWindow"
 * path=".core.contentResource.closeWindow"
 */
public final class CreateContentResourceAction extends BaseAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        ServletContext servletContext = session.getServletContext();
        boolean closeWindowAfterCreated = Boolean.TRUE.equals(session.getAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY));

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);

        if ( isCancelled(request) ) {
            resetToken(request);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);
            if (closeWindowAfterCreated) {
                request.setAttribute("createdContentResource", Boolean.FALSE);
                return mapping.findForward("closeWindow");
            }
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) form;

        ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(servletContext);

		FormFile file = uploadContentResourceForm.getFile();
		if ( file == null || file.getFileName() == null || file.getFileName().trim().length() == 0 || file.getFileSize() == 0 ) {
			List supportedExtensions = resourceTypesManager.getSupportedExtensions();
			ActionMessages errors = new ActionMessages();
			errors.add("contentResourceUnsupportedExtension", new ActionMessage("core.contentResource.errors.unsupportedExtension", supportedExtensions.toString()));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}

		String fileName = file.getFileName();
		String resourceType = resourceTypesManager.getResourceTypeByFileName(fileName);
		String mimeType = resourceTypesManager.getMimeTypeByFileName(fileName);

        if (resourceType == null) {
            resourceType = Constants.RESOURCE_TYPE_FILE;
        }

        String requiredType = (String) session.getAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
        if (resourceTypesManager.getResourceTypeNameKey(requiredType) == null) {
            // unknown resource type, assume that everything is allowed
            requiredType = null;
        }
        if (!GenericValidator.isBlankOrNull(requiredType)) {
            if ( !resourceType.equalsIgnoreCase(requiredType) ) {
                file.destroy();
                List supportedExtensions = resourceTypesManager.getResourceTypeExtensions(requiredType);
                ActionMessages errors = new ActionMessages();
                errors.add("contentResourceWrongType", new ActionMessage("core.contentResource.errors.wrongType", supportedExtensions.toString()));
                saveErrors(request, errors);
                saveToken(request);
                return mapping.getInputForward();
            }
        }

        if ( log.isDebugEnabled() ) {
			log.debug("Uploaded file '" + fileName + "' (" + file.getFileSize() + " bytes) type=" + resourceType);
		}

        session.setAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY, uploadContentResourceForm);
        if ( resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_IMAGE) ) {

            //check for support
            try {
                ImageUtil.decodeImage(file.getFileData(), mimeType);
            } catch ( Exception ex ) {
                ActionMessages errors = new ActionMessages();
                errors.add("contentResourceUnsupportedOrCorrupted", new ActionMessage("core.contentResource.errors.unsupportedOrCorrupted"));
                saveErrors(request, errors);
                saveToken(request);
                return mapping.findForward("callCreateFile");
            }

            return mapping.findForward("callCreateImage");
        } else if ( resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_FILE) ) {
            return mapping.findForward("callCreateFile");
        } else if ( resourceType.equalsIgnoreCase(Constants.RESOURCE_TYPE_DOCUMENT) ) {

            //check for support
            String plainText;
            String determinedEncoding;
            try {
                PlainTextExtractor extractor = new PlainTextExtractor();
                plainText = extractor.extract(new ByteArrayInputStream(file.getFileData()), mimeType);
                determinedEncoding = extractor.getUsedEncoding();
            } catch ( Exception ex ) {
                ActionMessages errors = new ActionMessages();
                errors.add("contentResourceUnsupportedOrCorrupted", new ActionMessage("core.contentResource.errors.unsupportedOrCorrupted"));
                saveErrors(request, errors);
                saveToken(request);
                return mapping.findForward("callCreateFile");
            }
            Integer summarySize = GlobalProperties.getInstance(servlet.getServletContext()).getInteger(WebappConstants.DOCUMENT_SUMMARY_SIZE_KEY, new Integer(400));
            plainText = StringUtil.htmlEncode(StringUtil.shortenString(plainText, Math.min(plainText.length(), summarySize.intValue())));
            session.setAttribute(WebappConstants.CONTENT_DOCUMENT_NEW_SUMMARY_KEY, plainText);

            session.setAttribute(WebappConstants.CONTENT_DOCUMENT_ENCODING_KEY, determinedEncoding);

            return mapping.findForward("callCreateDocument");
        } else {
            throw new Exception("There are not action found for resource type=" + resourceType);
        }

	}
}